/*
 * Droplet.cpp
 *
 * Created: 5/11/2012 4:13:57 PM
 *  Author: common
 */ 
#define F_CPU 32000000UL

#include <avr/io.h>
#include <math.h>
#include <util/delay.h>

#include "motor.h"
#include "RGB_LED.h"
#include "pc_com.h"
#include "RGB_sensor.h"
#include "power.h"
#include "random.h"

extern uint8_t rsenbase,gsenbase,bsenbase;
char userPause = ' ';

void Config32MHzClock(void)
{
	// initialize clock source to be 32MHz internal oscillator (no PLL)
	CCP = CCP_IOREG_gc;							//Security Signature to modify clock
	OSC.CTRL = OSC_RC32MEN_bm;					// enable internal 32MHz oscillator
	while(!(OSC.STATUS & OSC_RC32MRDY_bm));		// wait for oscillator ready
	CCP = CCP_IOREG_gc;							//Security Signature to modify clock
	CLK.CTRL = 0x01;							//select sysclock 32MHz osc
}

int main(void)
{
	Config32MHzClock();
	
	motor_init();
	RGB_LED_init();
	rgb_sensor_init();
	leg_monitor_init();
	cap_monitor_init();
	pc_com_init();
	ir_com_init();
	random_init();
	
	set_blue_led(50); _delay_ms(250); led_off();
	_delay_ms(250); set_blue_led(50); _delay_ms(250); led_off();
	
	uint8_t sender = 0, r = 0xAA, loopnum = 0;
	while (0)
	{
		if (sender == 1)
		{
			r = rand_byte();
			set_red_led(r);
			USARTC0.DATA = USARTC1.DATA = USARTD0.DATA = USARTE0.DATA = USARTE1.DATA = USARTF0.DATA = r;
			printf("%i Sent %i\r\n", loopnum, r);
			_delay_ms(500);
		}
		else
		{
			if (USARTC0.STATUS & USART_RXCIF_bm) { r = USARTC0.DATA; printf("%i Received %i from direction 0\r\n", loopnum, r); }
			if (USARTC1.STATUS & USART_RXCIF_bm) { r = USARTC1.DATA; printf("%i Received %i from direction 1\r\n", loopnum, r); }
			if (USARTD0.STATUS & USART_RXCIF_bm) { r = USARTD0.DATA; printf("%i Received %i from direction 2\r\n", loopnum, r); }
			if (USARTE0.STATUS & USART_RXCIF_bm) { r = USARTE0.DATA; printf("%i Received %i from direction 3\r\n", loopnum, r); }
			if (USARTE1.STATUS & USART_RXCIF_bm) { r = USARTE1.DATA; printf("%i Received %i from direction 4\r\n", loopnum, r); }
			if (USARTF0.STATUS & USART_RXCIF_bm) { r = USARTF0.DATA; printf("%i Received %i from direction 5\r\n", loopnum, r); }
			set_red_led(r);
		}			
		loopnum++;
	}	
}